package com.baitiaojun.video.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.user.UserInfo;
import com.baitiaojun.api.domain.video.CollectionGroup;
import com.baitiaojun.api.domain.video.Video;
import com.baitiaojun.api.domain.video.VideoCollection;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.AESUtil;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.SnowFlakeUtil;
import com.baitiaojun.api.vo.CollectionGroupItem;
import com.baitiaojun.api.vo.CollectionGroupSubWrapper;
import com.baitiaojun.api.vo.CollectionGroupWrapper;
import com.baitiaojun.video.config.properties.CollectionGroupProperties;
import com.baitiaojun.video.feign.UserFeign;
import com.baitiaojun.video.mapper.CollectionGroupMapper;
import com.baitiaojun.video.service.CollectionGroupService;
import com.baitiaojun.video.service.VideoCollectionService;
import com.baitiaojun.video.service.VideoService;
import com.baitiaojun.video.support.RedisSupport;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @类名 CollectionGroupServiceImpl
 * @描述 TODO 添加视频分组需要做逻辑判断是否有自定义图片，没有就添加默认图片
 * @作者 白条君
 * @创建日期 2022/12/22 20:53
 * @版本 1.0
 */
@Service
public class CollectionGroupServiceImpl implements CollectionGroupService {

    @Resource
    private CollectionGroupMapper collectionGroupMapper;

    @Resource
    private RedisSupport redisSupport;

    @Autowired
    private CollectionGroupService collectionGroupService;

    @Resource
    private CollectionGroupProperties collectionGroupProperties;

    @Autowired
    private VideoService videoService;

    @Autowired
    private VideoCollectionService videoCollectionService;

    @Autowired
    private UserFeign userFeign;

    @Override
    public void addCollectionGroup(CollectionGroup collectionGroup, Long userId, String nick) throws Exception {
        String name = collectionGroup.getName();
        if (StringUtils.equals("", name)) {
            throw new ConditionException("创建的收藏夹名称不能为空");
        }
        if (!StringUtil.isNullOrEmpty(collectionGroup.getThumbnail())) {
            AESUtil aesUtil = AESUtil.lazyGetAesUtil();
            collectionGroup.setThumbnail(aesUtil.decrypt(collectionGroup.getThumbnail()));
        }
        collectionGroup.setId(SnowFlakeUtil.getNextId());
        collectionGroup.setCreatetime(new Date());
        collectionGroup.setType(ConstantUtil.CollectionType.CUSTOM.getType());
        collectionGroup.setUserid(userId);
        //解密thumbnail
        int res = collectionGroupMapper.insertSelective(collectionGroup);
        if (res == 0) {
            throw new ConditionException("新建收藏夹失败");
        }
        redisSupport.setValue(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId
                                , getVideoCollectionContentsFromMysql(userId, nick)
                                , 1
                                , TimeUnit.DAYS);
    }

    @Override
    public void updateCollectionGroup(CollectionGroup collectionGroup, Long userId) throws Exception {
        Long groupId = collectionGroup.getId();
        if (ObjectUtils.equals("", groupId)) {
            throw new ConditionException("收藏夹名称id不能为空");
        }
        collectionGroup.setUpdatetime(new Date());
        if (!StringUtil.isNullOrEmpty(collectionGroup.getThumbnail())) {
            AESUtil aesUtil = AESUtil.lazyGetAesUtil();
            collectionGroup.setThumbnail(aesUtil.decrypt(collectionGroup.getThumbnail()));
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
        int res = collectionGroupMapper.updateCollectionGroup(collectionGroup);
        if (res == 0) {
            throw new ConditionException("收藏夹更新失败");
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
    }

    @Override
    public List<CollectionGroup> getCollectionGroups(Long userId) {
        return collectionGroupMapper.selectByUserId(userId);
    }

    @Override
    @Transactional
    public void cancelCollectionGroup(Long groupId, Long userId) throws Exception {
        if (ObjectUtils.equals("", groupId)) {
            throw new ConditionException("收藏夹名称id不能为空");
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
        int res = collectionGroupMapper.deleteByPrimaryKey(groupId);
        if (res == 0) {
            throw new ConditionException("删除收藏夹失败");
        }
        //查找收藏夹是否为空
        Integer isExists = videoCollectionService.isExistsVideoCollections(groupId);
        if (ObjectUtils.isNotEmpty(isExists)) {
            videoCollectionService.batchCancelVideoCollections(groupId);
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
    }

    @Override
    public List<CollectionGroupWrapper> getCollectionGroupContents(Long userId, String nick) throws Exception {
        //从redis获取数据
        Object collectionGroupsFromRedis = redisSupport.getValue(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
        if (Objects.nonNull(collectionGroupsFromRedis)) {
            return JSONObject.parseArray(JSONObject.toJSONString(collectionGroupsFromRedis), CollectionGroupWrapper.class);
        }
        //如果redis中获取的collectionGroupList长度为空，从mysql获取数据
        List<CollectionGroupWrapper> collectionGroupWrapper = getVideoCollectionContentsFromMysql(userId, nick);
        redisSupport.setValue(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId
                , getVideoCollectionContentsFromMysql(userId, nick)
                , 1
                , TimeUnit.DAYS);
        return collectionGroupWrapper;
    }

    @Override
    public List<CollectionGroupWrapper> getVideoCollectionContentsFromMysql(Long userId, String nick) throws Exception {
        List<CollectionGroupWrapper> collectionGroupWrappers = new ArrayList<>();
        //添加默认收藏夹
        CollectionGroupWrapper defaultCollectionGroupWrapper = new CollectionGroupWrapper();
        defaultCollectionGroupWrapper.setId(collectionGroupProperties.getId()[0]);
        defaultCollectionGroupWrapper.setName(collectionGroupProperties.getName()[0]);
        defaultCollectionGroupWrapper.setType(collectionGroupProperties.getType()[0]);
        defaultCollectionGroupWrapper.setCollectionGroupItems(new ArrayList<>());
        collectionGroupWrappers.add(defaultCollectionGroupWrapper);
        //创建自定义分组
        CollectionGroupWrapper customCollectionGroupWrapper = new CollectionGroupWrapper();
        customCollectionGroupWrapper.setId(collectionGroupProperties.getId()[1]);
        customCollectionGroupWrapper.setName(collectionGroupProperties.getName()[1]);
        customCollectionGroupWrapper.setType(collectionGroupProperties.getType()[1]);
        customCollectionGroupWrapper.setSubCollectionGroups(new ArrayList<>());
        collectionGroupWrappers.add(customCollectionGroupWrapper);
        //获得所有当前用户自定义的收藏夹
        List<CollectionGroup> collectionGroupList = collectionGroupService.getCollectionGroups(userId);
        customCollectionGroupWrapper.setCount(collectionGroupList.size());
        //获取当前用户收藏的视频，并对videoCollections列表排序
        List<VideoCollection> videoCollections = videoCollectionService
                .selectVideoCollectionByUserId(userId).stream()
                .sorted(Comparator.comparing(VideoCollection::getCreatetime)).collect(Collectors.toList());
        //获取nick，并赋值到对应的nick
        List<UserInfo> userInfos = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(videoCollections)) {
            Set<Long> userIds = videoCollections.stream().map(VideoCollection::getUserid).collect(Collectors.toSet());
            userInfos = userFeign.batchGetUserInfoByUserIdsSet(userIds);
        }
        //相关对象定义
        CollectionGroupItem item;
        List<CollectionGroupItem> sameGroupVideoCollection;
        List<CollectionGroupSubWrapper> customCollectionGroupList = customCollectionGroupWrapper.getSubCollectionGroups();
        //对自定义收藏夹的收藏视频归类
        AESUtil aesUtil = AESUtil.lazyGetAesUtil();
        for (CollectionGroup collectionGroup : collectionGroupList) {
            sameGroupVideoCollection = new ArrayList<>();
            for (VideoCollection videoCollection : videoCollections) {
                if (Objects.equals(videoCollection.getGroupid(), collectionGroup.getId())) {
                    //获取视频信息
                    Long videoId = videoCollection.getVideoid();
                    Video video = videoService.getVideoById(videoId);
                    //创建返回对象
                    item= new CollectionGroupItem();
                    item.setId(video.getId());
                    item.setTitle(video.getTitle());
                    String thumbnail = video.getThumbnail();
                    if (!StringUtil.isNullOrEmpty(thumbnail)) {
                        item.setThumbnail(aesUtil.encrypt(video.getThumbnail()));
                    }
                    item.setDuration(video.getDuration());
                    item.setCreatetime(video.getCreatetime());
                    for (UserInfo userInfo : userInfos) {
                        if (userInfo.getUserid().equals(video.getUserId())) {
                            item.setCreator(userInfo.getNick());
                        }
                    }
                    sameGroupVideoCollection.add(item);
                }
            }
            //同一个自定义分组视频收藏集合收集到同一个自定义分组
            CollectionGroupSubWrapper subWrapper = new CollectionGroupSubWrapper();
            subWrapper.setId(collectionGroup.getId());
            subWrapper.setTitle(collectionGroup.getName());
            String thumbnail = collectionGroup.getThumbnail();
            if (!StringUtil.isNullOrEmpty(thumbnail)) {
                subWrapper.setThumbnail(aesUtil.encrypt(thumbnail));
            }
            subWrapper.setCreator(nick);
            subWrapper.setCount(sameGroupVideoCollection.size());
            subWrapper.setCreatetime(collectionGroup.getCreatetime());
            subWrapper.setDescription(collectionGroup.getDescription());
            subWrapper.setSameGroupVideoCollection(sameGroupVideoCollection);
            customCollectionGroupList.add(subWrapper);
        }
        //将默认收藏夹的视频添加到默认收藏夹
        List<CollectionGroupItem> defaultCollectionGroupList = defaultCollectionGroupWrapper.getCollectionGroupItems();
        for (VideoCollection videoCollection : videoCollections) {
            if (Objects.equals(videoCollection.getGroupid(), defaultCollectionGroupWrapper.getId())) {
                //获取视频信息
                Video video = videoService.getVideoById(videoCollection.getVideoid());
                //创建返回对象
                item= new CollectionGroupItem();
                item.setId(video.getId());
                item.setTitle(video.getTitle());
                String thumbnail = video.getThumbnail();
                if (!StringUtil.isNullOrEmpty(thumbnail)) {
                    item.setThumbnail(aesUtil.encrypt(video.getThumbnail()));
                }
                item.setDuration(video.getDuration());
                item.setCreator(video.getCreator());
                item.setCreatetime(video.getCreatetime());
                for (UserInfo userInfo : userInfos) {
                    if (userInfo.getUserid().equals(video.getUserId())) {
                        item.setCreator(userInfo.getNick());
                    }
                }
                defaultCollectionGroupList.add(item);
            }
        }
        defaultCollectionGroupWrapper.setCount(defaultCollectionGroupList.size());
        //重新定义一个集合返回
        return collectionGroupWrappers;
    }
}
